<template>
  <el-table
    :data="tableData"
    border
    style="width: 100%"
  >
    <el-table-column prop="_id" label="ID" width="220"></el-table-column>
    <el-table-column prop="name" label="广告位名称"></el-table-column>
    <el-table-column label="个数">
      <template slot-scope="scope">{{scope.row.items.length}}</template>
    </el-table-column>
    <el-table-column
      label="操作"
      width="100">
      <template slot-scope="scope">
        <el-button @click="handleEdit(scope.row._id)" type="text" size="small">编辑</el-button>
        <el-button @click="handleDelete(scope.row)" type="text" size="small">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
  export default {
    data() {
      return {
        tableData: []
      }
    },
    created() {
        this.fetch()
    },
    methods: {
      handleEdit(id) {
        this.$router.push(`/ads/edit/${id}`)
      },
      async fetch() {
          const res = await this.$http.get('curd/ads')
          this.tableData = res.data
      },
      async handleDelete(row) {
        const {name, _id: id} = row
        this.$confirm(`确认删除${name}?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await this.$http.delete(`curd/ads/${id}`)
          this.fetch()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      }
    },
  }
</script>